package cn.kennylee.codehub.feign.interceptor.biz.apiimpl;

import cn.kennylee.codehub.feign.interceptor.api.HelloApi;
import cn.kennylee.codehub.feign.interceptor.dto.HelloDto;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p> HelloApi feign实现类 </p>
 * <p>Created on 2024/1/15.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
@Component
@Primary // 建议指定，因为HelloApi的实现类可能有多个，需要指定一个实现类
@Slf4j
public class HelloApiImpl implements HelloApi {

    @Override
    public HelloDto hello(String name) {
        log.info("我在HelloApiImpl");
        return HelloDto.builder()
            .name(name).headers(getHeaders())
            .build();
    }

    @NonNull
    public static Map<String, String> getHeaders() {
        final ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(servletRequestAttributes).getRequest();

        final Map<String, String> headers = new HashMap<>(16);

        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            headers.put(headerName, headerValue);
        }
        return headers;
    }
}
